const { querySql, queryOne } = require("../utils/sql");
// 生成随机id
const intformat = require("biguint-format"),
  FlakeId = require("flake-idgen");
// 令牌
// const auth = require("../utils/auth-jwt");
const jwt = require("jsonwebtoken");
const constant = require("../utils/constant");
const multiparty = require("multiparty");
const fs = require("fs");
const fse = require("fs-extra");

const path = require("path");

// 定义表明
const TABLEName = "users";
// 登录方法
const login = (req, res) => {
  const { username, password } = req.body;
  // console.log("params",params)

  const sqpStr = `select * from ${TABLEName} where username='${username}' and password='${password}'`;
  const selectQuery = `select * from ${TABLEName} where username='${username}' and password='${password}'`;

  querySql(sqpStr).then(async (user) => {
    if (!user || user.length === 0) {
      res.json({
        code: -1,
        msg: "账号或密码错误",
        data: null,
      });
    } else {
      // 登录成功，签发一个token并返回给前端
      let data = await querySql(selectQuery);
      let { id, username, createtime, permissions, nickname, avatar } = data[0];
      const token =
        "Bearer " +
        jwt.sign(
          { id, username, createtime, permissions, nickname, avatar },
          constant.PRIVATE_KEY,
          {
            expiresIn: constant.JWT_EXPIRED,
          }
        );
      res.json({
        code: 0,
        msg: "登录成功",
        data: {
          token: token,
          userData: { id, username, createtime, permissions, nickname, avatar },
        },
      });
    }
  });
};

// 注册接口
const register = async (req, res) => {
  const { username, password } = req.body;
  const id = intformat(new FlakeId().next(), "dec");
  //   7226975702233382912
  //   9223372036854775807

  const insertQuery = `insert into ${TABLEName}(id, username, password) values(${id}, '${username}', '${password}')`;
  const selectQuery = `select * from ${TABLEName} where username='${username}' and password='${password}'`;
  let data = await findUser(username);
  if (data) {
    return res.json({
      code: -1,
      msg: "用户已存在",
      data: null,
    });
  } else {
    let result = await querySql(insertQuery);
    if (!result || result.length === 0) {
      return res.json({
        code: -1,
        msg: "注册失败",
        data: null,
      });
    }
    let data = await querySql(selectQuery);
    // console.log("data=>", data);

    let { id, username, createtime, permissions, nickname, avatar } = data[0];
    const token = generateToken({
      id,
      username,
      createtime,
      permissions,
      nickname,
      avatar,
    });

    res.json({
      code: 0,
      msg: "注册成功",
      data: {
        token,
        userData: { id, username, createtime, permissions, nickname, avatar },
      },
    });
  }
};
// 校验用户名和密码
function validateUser(username, oldPassword) {
  const query = `select id, username from ${TABLEName} where username='${username}' and password='${oldPassword}'`;
  return queryOne(query);
}
// 获取编辑用户信息
const editUser = async (req, res) => {
  try {
    const form = new multiparty.Form();
    form.parse(req, async (err, otherParams, files) => {
      if (err) {
        res.send({ code: -1, msg: "修改失败", data: err });
        return false;
      }
      // console.log("rer", fields, files);
      let { id, username, password, permissions, nickname } = otherParams;
      // console.log({ username, password, permissions, nickname });
      // Object.keys(otherParams).forEach((keys) => {
      if (!id) {
        return res
          .status(400)
          .send({ code: -1, msg: "必要参数未填写", data: null });
      }
      // });

      let { avatar } = files;
      // console.log(avatar);
      let sql = `update users set username = "${username}", password = "${password}", permissions = '${permissions}', nickname = "${nickname}"`;
      // 检查 /public/users/id临时文件目录 是否存在，如果不存在则创建它。
      let url = `/public/users`;
      const user_avatar_path = path.join(__dirname, "../", url);
      if (!avatar || !avatar[0]?.path) {
        sql += ` WHERE id = ${id}`;
        let result = await querySql(sql);
        if (result?.affectedRows == 1) {
          let user = await querySql("select * from users where id = " + id);
          // console.log("user", user);
          let {
            id: userId,
            username,
            createtime,
            permissions,
            nickname,
            avatar,
          } = user[0];
          return res.send({
            code: 0,
            msg: "用户信息修改成功。",
            data: {
              id: userId,
              username,
              createtime,
              permissions,
              nickname,
              avatar,
            },
          });
        }
      }
      var rbuf = fs.readFileSync(avatar[0].path);
      // console.log("rbuf",rbuf);
      if (!fse.existsSync(user_avatar_path)) {
        await fse.mkdirs(user_avatar_path);
      }
      fs.writeFile(
        user_avatar_path +
          `/${id}avatar.${avatar[0].headers["content-type"].split("/")[1]}`,
        rbuf,
        async (err) => {
          if (err) {
            console.error("err=>", err);
          }
          // if (avatar[0].path) {
          sql += `, avatar = "/users/${id}avatar.${
            avatar[0].headers["content-type"].split("/")[1]
          }"`;
          // }
          sql += ` WHERE id = ${id}`;
          let result = await querySql(sql);
          if (result?.affectedRows == 1) {
            let user = await querySql("select * from users where id = " + id);
            // console.log("user", user);
            let {
              id: userId,
              username,
              createtime,
              permissions,
              nickname,
              avatar,
            } = user[0];
            res.send({
              code: 0,
              msg: "用户信息修改成功。",
              data: {
                id: userId,
                username,
                createtime,
                permissions,
                nickname,
                avatar,
              },
            });
          }
        }
      );
    });
  } catch (err) {
    res.send({ code: -1, msg: "用户信息修改失败", data: err });
  }
};
// 通过用户名查询用户信息
function findUser(username) {
  const query = `select id, username from ${TABLEName} where username='${username}'`;
  return queryOne(query);
}
module.exports = {
  login,
  register,
  editUser,
};
